package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/list")
    public PageDTO list(@RequestParam("page") int page, @RequestParam("size") int size) {
        //1.构造分页条件
        Page<Item> pageInfo = new Page<>(page, size);
        //2.构建条件构造器
        LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
        //3.根据更新时间倒序排序
        lqw.orderByAsc(Item::getUpdateTime);
        //4.执行分页查询
        itemService.page(pageInfo, lqw);
        //5.返回结果
        return new PageDTO(pageInfo.getTotal(), pageInfo.getRecords());
    }

    @GetMapping("/{id}")
    public Item getById(@PathVariable("id") Long id) {
        LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Item::getId, id);
        lqw.orderByDesc(Item::getUpdateTime);
        Item item = itemService.getById(id);
        return item;
    }

    @PostMapping
    public void saveItem(@RequestBody Item item) {
        boolean flag = itemService.save(item);
        System.err.println(flag ? "新增商品成功！" : "新增商品失败！");
        rabbitTemplate.convertAndSend("hmall.topic", "hmall.insert", item.getId());
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id, @PathVariable Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);

    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Long id){
        boolean flag = itemService.removeById(id);
        System.err.println(flag ? "删除商品成功！" : "删除商品失败！");
        rabbitTemplate.convertAndSend("hmall.topic", "hmall.delete", id);
    }

    @PutMapping
    public void updateById(@RequestBody Item item){
        boolean flag = itemService.updateById(item);
        System.err.println(flag ? "修改商品成功！" : "修改商品失败！");
        rabbitTemplate.convertAndSend("hmall.topic", "hmall.insert", item.getId());
    }
}
